package io.github.wx.common.redis;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.redis.Redis;

/**
 * Created by jie on 2017/4/5.
 * 根据CacheName清除
 * 必须配合 @CacheName 使用
 */
public class RedisEvictInterceptor implements Interceptor {
    private static final String prefixKey = "intercept_";

    final public void intercept(Invocation inv) {
        inv.invoke();
        Redis.use().del(buildCacheName(inv));
    }

    private String buildCacheName(Invocation inv) {
        CacheName cacheName = inv.getMethod().getAnnotation(CacheName.class);
        if (cacheName != null)
            return prefixKey + cacheName.value();

        cacheName = inv.getController().getClass().getAnnotation(CacheName.class);
        if (cacheName == null)
            throw new RuntimeException("EvictInterceptor need CacheName annotation in controller.");
        return prefixKey + cacheName.value();
    }
}
